package com.fjh.springboot_01.controller;

import com.fjh.springboot_01.pojo.ChatMsg;
import com.fjh.springboot_01.service.MessageService;
import com.fjh.springboot_01.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/chat")
public class WebSocketController {

    @Autowired
    private MessageService messageService;

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    @Autowired
    private JwtUtil jwtUtil;

    // 发送私聊消息
    @MessageMapping("/chat.sendMessage")
    public void sendMessage(@Payload ChatMsg chatMsg) {
        try {
            // 保存消息到数据库
            messageService.handleSendMessage(chatMsg);
            
            // 发送消息给接收者
            String destination = String.format("/user/%s/queue/messages", chatMsg.getReceiveUserId());
            simpMessagingTemplate.convertAndSend(destination, chatMsg);
            
            // 发送消息给发送者（用于确认消息已发送）
            String senderDestination = String.format("/user/%s/queue/messages", chatMsg.getSendUserId());
            simpMessagingTemplate.convertAndSend(senderDestination, chatMsg);
            
            System.out.println("消息已发送 - 发送者: " + chatMsg.getSendUserId() + 
                             ", 接收者: " + chatMsg.getReceiveUserId() + 
                             ", 内容: " + chatMsg.getSendText());
        } catch (Exception e) {
            System.err.println("发送消息失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 发送好友请求通知
    @MessageMapping("/notification.sendNotification")
    public void sendNotification(String notification) {
        messageService.handleSendNotification(notification);
    }
    
    // 处理视频通话请求
    @MessageMapping("/chat.videoOffer")
    public void handleVideoOffer(@Payload ChatMsg chatMsg) {
        try {
            System.out.println("收到视频通话请求 - 发送者: " + chatMsg.getSendUserId() + 
                             ", 接收者: " + chatMsg.getReceiveUserId());
            
            // 发送给接收者
            String destination = String.format("/user/%s/queue/messages", chatMsg.getReceiveUserId());
            simpMessagingTemplate.convertAndSend(destination, chatMsg);
        } catch (Exception e) {
            System.err.println("处理视频通话请求失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    // 处理视频通话应答
    @MessageMapping("/chat.videoAnswer")
    public void handleVideoAnswer(@Payload ChatMsg chatMsg) {
        try {
            System.out.println("收到视频通话应答 - 发送者: " + chatMsg.getSendUserId() + 
                             ", 接收者: " + chatMsg.getReceiveUserId());
            
            // 发送给接收者
            String destination = String.format("/user/%s/queue/messages", chatMsg.getReceiveUserId());
            simpMessagingTemplate.convertAndSend(destination, chatMsg);
        } catch (Exception e) {
            System.err.println("处理视频通话应答失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    // 处理ICE候选者信息
    @MessageMapping("/chat.iceCandidate")
    public void handleIceCandidate(@Payload ChatMsg chatMsg) {
        try {
            System.out.println("收到ICE候选者信息 - 发送者: " + chatMsg.getSendUserId() + 
                             ", 接收者: " + chatMsg.getReceiveUserId());
            
            // 发送给接收者
            String destination = String.format("/user/%s/queue/messages", chatMsg.getReceiveUserId());
            simpMessagingTemplate.convertAndSend(destination, chatMsg);
        } catch (Exception e) {
            System.err.println("处理ICE候选者信息失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    // 处理挂断视频通话
    @MessageMapping("/chat.videoHangup")
    public void handleVideoHangup(@Payload ChatMsg chatMsg) {
        try {
            System.out.println("收到挂断视频通话请求 - 发送者: " + chatMsg.getSendUserId() + 
                             ", 接收者: " + chatMsg.getReceiveUserId());
            
            // 发送给接收者
            String destination = String.format("/user/%s/queue/messages", chatMsg.getReceiveUserId());
            simpMessagingTemplate.convertAndSend(destination, chatMsg);
        } catch (Exception e) {
            System.err.println("处理挂断视频通话请求失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 获取聊天历史记录
    @GetMapping("/history")
    public ResponseEntity<?> getChatHistory(
            HttpServletRequest request,
            @RequestParam String userId,
            @RequestParam String friendId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int pageSize) {
        
        try {
            System.out.println("开始处理获取历史记录请求");
            
            // 获取请求头中的token
            String token = request.getHeader("Authorization");
            System.out.println("收到的token: " + token);
            
            if (token == null) {
                System.out.println("未提供token");
                return ResponseEntity.status(401).body("未提供认证token");
            }

            // 验证token
            if (!jwtUtil.validateToken(token)) {
                System.out.println("token验证失败");
                return ResponseEntity.status(401).body("token已过期或无效");
            }

            // 从token中获取用户ID
            String tokenUserId = jwtUtil.getUserIdFromToken(token);
            System.out.println("从token中获取的用户ID: " + tokenUserId);
            
            // 验证请求的用户ID是否匹配token中的用户ID
            if (!userId.equals(tokenUserId)) {
                System.out.println("用户ID不匹配 - 请求ID: " + userId + ", Token ID: " + tokenUserId);
                return ResponseEntity.status(403).body("无权访问该用户的聊天记录");
            }

            System.out.println("接收到获取历史记录请求 - userId: " + userId + 
                             ", friendId: " + friendId + 
                             ", page: " + page + 
                             ", pageSize: " + pageSize);
            
            List<ChatMsg> history = messageService.getChatHistory(userId, friendId, page, pageSize);
            return ResponseEntity.ok(history);
        } catch (Exception e) {
            System.err.println("获取聊天历史记录失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(500).body("获取聊天历史记录失败: " + e.getMessage());
        }
    }
}
